<template>
  <div class="container">
    <div class="app-container">
      <!--
        el-tree
        data是数据(树形结构)
        props是展示规则
          label 显示文字的是哪个字段，默认是label
          children 子级数据是存储在哪个字段，默认是children
        default-expand-all 默认展开所有
      -->
      <el-tree default-expand-all :data="data">
        <el-row slot-scope="{data}" style="width:100%;" type="flex" justify="space-around">
          <el-col>{{ data.name }}</el-col>
          <el-col :span="4">
            <el-row type="flex">
              <el-col :span="12">{{ data.managerName }}</el-col>
              <el-dropdown @command="operateDept($event,data.id)">
                <span>
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </el-col>
        </el-row>
      </el-tree>
      <!-- 绘制弹框 -->
      <!-- <add-dept :show-dialog="showDialog" @update:showDialog="showDialog=$event" /> -->
      <!-- <haha  title.sync="infotit" /> -->
      <!-- <haha :title="infotit" @update:title="infotit = $event" > -->
      <!-- ===> haha组件内部 自定义属性叫做title 自定义事件叫做 update:title-->
      <add-dept ref="addDept" :parent-id="currentId" :show-dialog.sync="showDialog" @updateList="initData" />
    </div>
  </div>
</template>
<script>
import { delDepartmentApi, getDepartmentListApi } from '@/api/department'
import { transListToTreeData } from '@/utils'
import AddDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: { AddDept },
  data() {
    return {
      // 定义变量
      data: [],
      // 弹框控制变量
      showDialog: false,
      // 点击行的ID
      currentId: ''
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      // 请求数据(封装API函数)
      const res = await getDepartmentListApi()
      // 数据加工处理(整理成树)
      const result = transListToTreeData(res, 0)
      // 赋值变量
      this.data = result
    },
    // 下拉点击
    async operateDept(val, rowId) {
      this.currentId = rowId
      // 添加子部门逻辑
      if (val === 'add') {
        this.showDialog = true
      }
      if (val === 'edit') {
        // 获取数据逻辑，回显
        await this.$refs.addDept.reviewFormData(rowId)
        // 弹框打开
        this.showDialog = true
      }
      if (val === 'del') {
        // 删除
        await this.$confirm('确认删除吗？')
        await delDepartmentApi(rowId)
        this.$message.success('删除成功')
        this.initData()
      }
    }
  }
}
</script>
<style scoped>
.app-container{
  padding:50px 100px;
}
</style>
